<template>
  <div>
    <el-dialog width="60%" class="WholeScroll" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-liuchengguanli-2"></i>
        <span>{{ title }}</span>
      </span>
      <div class="WholeScroll" style="max-height: 550px; overflow: auto">
        <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules">
          <el-tabs v-model="activeName">
            <el-row>
              <el-col :span="24">
                <el-form-item label="选择工程类型" prop="gclx" :label-width="formlabelWidth" required>
                  <el-select style="width: 100%" v-model="formBaseData.gclx" filterable :disabled="detailType === 'check' || detailType === 'edit'" @change="onSelectGclx">
                    <el-option v-for="(item, i) in selectList.enginTypeList" :key="i" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="选择批复项" prop="approveId" :label-width="formlabelWidth">
                  <el-select style="width: 100%" v-model="formBaseData.approveId" filterable :disabled="detailType === 'check' || detailType === 'edit'">
                    <el-option v-for="(item, i) in selectList.approval" :key="i" :label="item.name" :value="item.dictId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="工作内容" prop="workContent" :label-width="formlabelWidth">
                  <el-input v-model="formBaseData.workContent" placeholder="请输入工作内容" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="对接部门/单位" prop="unit" :label-width="formlabelWidth">
                  <el-input v-model="formBaseData.unit" placeholder="请输入对接部门/单位" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="办理用时（工作日）" prop="timeUse" :label-width="formlabelWidth">
                  <el-input v-model="formBaseData.timeUse" placeholder="请输入办理用时（工作日）" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="依据文件" prop="fileName" :label-width="formlabelWidth">
                  <el-input v-model="formBaseData.fileName" placeholder="请输入依据文件" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="排序" prop="sort" :label-width="formlabelWidth">
                  <el-input v-model="formBaseData.sort" placeholder="请输入排序号" :disabled="detailType === 'check' || detailType === 'approve'"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item prop="mark" label="备注" :label-width="formlabelWidth">
                  <el-input class="fill" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="" v-model="formBaseData.mark" :disabled="
                      detailType === 'check' || detailType === 'approve'
                    ">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tabs>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <!--api操作按钮 除去上报-->
        <!--新建和编辑的暂存上报-->

        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })"><i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')"><i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const urlBussBase = 'contractapply'
import { submitSetting, resubmitSetting, getOneForSetting, getApprovals, getAllApprovalDict } from '@/api/buss/frontProject'
import crudDict from '@/api/system/dict'
export default {
  // name: 'checknotice-manage-detail',
  name: urlBussBase + '-manage-detail',
  components: {
    //  审核用
    // audit_component: require("../../../../../components/audit/audit").default
  },
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {},
      },
    },
  },
  watch: {
    postDetail(value) {
      console.log(value)
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      // 详情的流程操作处理
      this.formBaseData.companyId = value.companyId
      this.formBaseData.projectId = value.projectId
      this.formBaseData.approvalType = value.approvalType
      if (this.$parent.search.gclx) {
        this.formBaseData.gclx = this.$parent.search.gclx
      }
      this.detailActions.splice(0, this.detailActions.length)
      // 详情id
      this.detailId = value.detailId === undefined ? '0' : value.detailId
      this.getEnginTypeList()
      // this.getApprovals()
      this.getAllApprovalDict()
      if (this.detailType !== 'build') {
        // 获取详情请求
        this.getDetail()
      }

      if (this.detailType === 'build') {
        this.title = '新增批复项工作内容配置'
      }
      if (this.detailType === 'edit') {
        this.title = '编辑批复项工作内容配置'
      }
      if (this.detailType == 'check') {
        this.title = '查看批复项工作内容配置'
      }
    },
  },
  data() {
    return {
      fileList: [],
      urlBussBase: 'contractapply',
      newDetName: '',
      isLoading: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '145px', // 表单左侧标题宽度
      formlabelRightWidth: '150px', // 表单左侧标题宽度
      formlabelWidth2: '120px', // 表单左侧标题宽度
      title: '',
      activeName: 'first',
      // 所有下拉框列表的集合
      selectList: {
        approval: [],
        enginTypeList: []
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      // 表单基本信息内容
      formBaseData: {
        gclx: '',
        approveId: '',
        workContent: '',
        unit: '',
        timeUse: '',
        mark: '',
        fileName: '',
        sort: '',
        approvalType: '',
        approvalUnit: '',
        docNumber: '',
      },
      // 表单基本信息验证
      formBaseRules: {
        approveId: [
          { required: true, message: '请选择' + '批复项', trigger: 'blur' },
        ],
        workContent: [
          { required: true, message: '请输入' + '工作内容', trigger: 'blur' },
        ],
        sort: [
          { required: true, message: '请输入' + '排序号', trigger: 'blur' },
        ]
      },
      //  是否需要出现标段
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'approvalItem',
          part: 'one',
          compoName: 'fileOne'
        }
      },
      itemlabelList: []
    }
  },

  filters: {
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },
  },
  created() {
    // 借地区域 api
    // this.getLandAreaList()
    // 土地类型
    /*   this.getLandTypeList()
    // 阶段类型
    this.getStageList()*/
    // this.getDeptName()
    // this.initDeptName()
    // this.getTypeList()
    // this.getContractSources()
    // this.getMoldList()
    // // this.getNatureList()
    // this.getFinanceList()
    // this.getSectionList()
    // this.getCompanyList()
    // this.getDepts()
    // this.getScopeProjects()
    // this.getScopeProjects()
  },
  methods: {
    getEnginTypeList() {
      crudDict.getByCode('enginType').then(res => {
        if (res.code === 200) {
          this.selectList.enginTypeList = []
          for (let i in res.data) {
            this.selectList.enginTypeList.push({ 'value': res.data[i].id, 'label': res.data[i].name });
          }
        }
      })
    },
    // 获取字典数，填充项
    getAllApprovalDict() {
      this.itemlabelList = {
        'ff808081877818f501894d0f97540086': [],
        'ff808081877818f501894d0fb6c30087': [],
        'ff8080818bf1932a018bfa1c9647012f': [],
        '': []
      }
      getAllApprovalDict().then(res => {
        res.data.map(e => {
          //标签字典项
          let obj = { name: e.approvalName, dictId: e.dictId }
          let labelA = ['ghxz', 'tdys', 'wwbh', 'yfklz', 'dzzhpg', 'shwdxpj', 'zjlyzm', 'gkpf', 'gkwb', 'gkzx', 'gkpsh', 'ccckwyys', 'cbsjpf', 'gspg', 'gssh', 'cbsjwb', 'cbsjzx', 'cbsjpsh', 'thlz', 'fhyxpj', 'stbcbg', 'hjyxpj', 'trqgxap', 'dcxkwyys', 'sgtpf', 'sgtsjwb', 'sgtsjzx', 'sgtsjps', 'ghydxkz', 'sgzb']
          let labelB = ['ghxz', 'tdys', 'shwdxpj', 'fahs', 'gkpf', 'gkwb', 'gkzx', 'cbsjpf', 'gspg', 'cbsjwb', 'cbsjzx', 'cbsjpsh', 'stbcbg', 'hjyxpj', 'fags', 'ghydxkz', 'ts', 'sgtsjwb2', 'xf', 'rf', 'jn', 'fl', 'gcghxkz', 'sgzb']
          let labelC = ['ghxz', 'tdys', 'shwdxpj', 'fahs', 'gkpf', 'gkwb', 'gkzx', 'cbsjpf', 'gspg', 'cbsjwb', 'cbsjzx', 'cbsjpsh', 'thlz', 'fhyxpj', 'stbcbg', 'hjyxpj', 'fags', 'ghydxkz', 'ghrkqzfazt', 'ts', 'sgtsjwb2', 'gcghxkz', 'sgzb']
          if (labelA.indexOf(e.approvalKey) !== -1) {//交通工程
            this.itemlabelList["ff808081877818f501894d0f97540086"].push(obj)
          }
          if (labelB.indexOf(e.approvalKey) !== -1) {//房建工程
            this.itemlabelList["ff808081877818f501894d0fb6c30087"].push(obj)
          }
          if (labelC.indexOf(e.approvalKey) !== -1) {//市政工程
            this.itemlabelList["ff8080818bf1932a018bfa1c9647012f"].push(obj)
          }
        })
        this.selectList.approval = this.itemlabelList[this.formBaseData.gclx]
      }).catch(e => {
        msgUtil.error2("批复项字典获取失败", e)
      })
    },
    onSelectGclx() {
      this.formBaseData.approveId = ''
      this.selectList.approval = this.itemlabelList[this.formBaseData.gclx]
    },
    /**
     * 加载文件
     **/
    loadFiles() {
      console.log(this.fileSystem, '========================')
      this.$nextTick(() => {
        for (let k in this.fileSystem) {
          let fileProp = this.fileSystem[k]
          this.$refs[fileProp.compoName].init()
        }
      })

    },
    /**
     * 保存文件
     */
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        this.$refs[fileProp.compoName].saveAll(this.detailId)
      }
    },
    changeFileOne(file) {
      this.$set(this, 'fileList', [...file])
    },
    changeCompanyGetDept() {
      this.$httpGetBuss(
        `/japi/contract/getDeptByCompany?id=${this.formBaseData.companyId}`
      )
        .then((res) => {
          if (res.data.status === 1) {
            this.selectList.depts = res.data.data
            this.getScopeProjects()
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          this.$messageError('合同列表获取失败!')
        })
    },
    /**
     * 获取当前用户能够看到的项目
     *
     * */
    getScopeProjects() {
      // this.$httpGetBuss(`/japi/contract/getAllProjectsByCompany`)
      //     .then((res) => {
      //         if (res.data.status == 1) {
      //             this.selectList.scopeProjects = res.data.data
      //         } else {
      //             throw res.data.message
      //         }
      //     })
      //     .catch((err) => {
      //         console.log('获取用户关联项目失败', err)
      //         this.$messageError('获取关联项目列表失败')
      //     })
      this.$httpGetBuss(
        `/japi/contract/getProjectsByCompanyId?id=${this.formBaseData.companyId}`
      )
        .then((res) => {
          if (res.data.status == 1) {
            this.selectList.scopeProjects = res.data.data
          } else {
            throw res.data.message
          }
        })
        .catch((err) => {
          console.log('获取用户关联项目失败', err)
          this.$messageError('获取关联项目列表失败')
        })
    },

    /**
     * 获取合同来源
     *
     * */
    getContractSources() {
      this.$httpPost(
        this.$store.state.httpHost.system +
        '/japi/dict/valuelabel/contractSource'
      )
        .then((res) => {
          if (res.data.status == 1) {
            this.selectList.contractSources = []

            res.data.list.forEach((item) => {
              this.$set(
                this.selectList.contractSources,
                this.selectList.contractSources.length,
                item
              )
            })
          } else {
            throw res.data.message
          }
        })
        .catch((err) => {
          console.log('获取用户关联项目失败', err)
          this.$messageError('获取关联项目列表失败')
        })
    },

    //  切换更改乙方单位是否使用系统
    changeSecondPartyRelation() {
      if (this.formBaseData.secondPartyRelation) {
        this.formBaseData.secondPartyNoRelationName = null
      } else {
        this.formBaseData.secondParty = null
      }
    },
    blurInputEvent() {
      if (this.formBaseData.amount) {
        this.formBaseData.amount = Number(this.formBaseData.amount).toFixed(2)
      }
    },
    blurInputEvent_feilv() {
      if (this.formBaseData.rate) {
        this.formBaseData.rate = Number(this.formBaseData.rate).toFixed(2)
      }
    },
    /**
     * 当切换是否总承包选择项时，如果由总承包切换为非总承包，清空标段选择项（变成单选
     *
     * */
    switchContractManagedSel() {
      this.formBaseData.sectionIds = []
      this.formBaseData.contractManageDeptName = null
      if (!this.formBaseData.contractManaged) {
        this.formBaseData.sectionMutiSelect = false
      } else {
        this.formBaseData.sectionMutiSelect = true
      }
    },
    /**
     * 获取乙方单位参与人
     * */
    getSecondPartUserTree(id, callback) {
      this.$httpGetBuss(
        `/japi/contract/getSecondPartUserTree?cid=${this.formBaseData.secondParty}`
      )
        .then((res) => {
          if (res.data.status == 1) {
            this.selectList.secondPartUserOpts = res.data.data
            this.formBaseData.memberUids = []
            if (callback) callback()
          } else {
            throw res.data.message
          }
        })
        .catch((err) => {
          console.log(err)
          this.$messageError('获取乙方单位参与人失败')
        })
    },
    addMulTag0(val) {
      this.formBaseData.memberUidsJson.splice(
        0,
        this.formBaseData.memberUidsJson.length
      )
      val.forEach((item) => {
        this.formBaseData.memberUidsJson.push(item)
      })
    },
    delTag0(val) {
      this.checkedownerRepresentativeUsers.splice(val, 1)
      this.$forceUpdate()
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
    },
    addTag0(val) {
      this.checkedownerRepresentativeUsers.push(val)
      this.$refs.cmsPopoverTree0.updateTree()
      this.$refs.cmsPopoverTree0.$forceUpdate()
      this.$forceUpdate()
    },

    changeSelectFinacialType(callback) {
      this.formBaseData.detyRate = ''
      this.selectList.finacialType.forEach((dict) => {
        if (dict.value == this.formBaseData.finacialType) {
          this.$httpPost(
            this.$store.state.httpHost.buss +
            '/japi/contract/getOneDic?id=' +
            this.formBaseData.finacialType
          ).then((res) => {
            if (res.data.status === 1) {
              this.formBaseData.dutyRate = res.data.data.tips
            }
          })

          // this.formBaseData.dutyRate = dict.tips
        }
      })
    },

    /**
     * 更改合同类型选择项时
     * 决定是否允许标段选择项
     *
     * */
    changeSelectType(callback) {
      // if (!this.formBaseData.projectIds) {
      //     this.$messageError('请先选择所属项目')
      //     this.formBaseData.type = null
      // }

      this.enableSectionSelection = false
      this.enableWhetherManageSelection = false
      // this.enableSection = false
      this.selectList.type.forEach((dict) => {
        if (dict.value == this.formBaseData.type) {
          if (
            dict.label == '工程类合同' ||
            dict.label == '监理类合同' ||
            dict.label == '代理合同' ||
            dict.label == '设计类合同' ||
            dict.label == '咨询评估类合同'
          ) {
            this.getProjectSection(this.formBaseData.projectIds, callback)
            this.enableSectionSelection = true
            this.formBaseData.sectionMutiSelect = false
          }
          if (dict.label == '工程类合同') {
            // this.formBaseData.contractManaged = false
            this.enableWhetherManageSelection = true
            this.enableSection = true

            this.formBaseData.sectionMutiSelect =
              this.formBaseData.contractManaged
          }
          if (dict.label == '监理类合同' || dict.label == '设计类合同') {
            this.enableSection = true
            this.formBaseData.sectionMutiSelect = true
          }
          //  根据选择类型过滤公司
          switch (dict.label) {
            case '工程类合同':
              this.selectList.companyListFiltered =
                this.selectList.companyList.filter(
                  (cp) => cp.typeName == '施工单位'
                )
              break
            case '监理类合同':
              this.selectList.companyListFiltered =
                this.selectList.companyList.filter(
                  (cp) => cp.typeName == '监理单位'
                )
              break
            case '设计类合同':
              this.selectList.companyListFiltered =
                this.selectList.companyList.filter(
                  (cp) => cp.typeName.indexOf('设计单位') != -1
                )
              break
            case '检测合同':
              this.selectList.companyListFiltered =
                this.selectList.companyList.filter(
                  (cp) => cp.typeName == '检测单位'
                )
              break
            case '跟踪审计合同':
              this.selectList.companyListFiltered =
                this.selectList.companyList.filter(
                  (cp) => cp.typeName == '审计单位'
                )
              break
            case '其它合同':
            default:
              this.selectList.companyListFiltered = this.selectList.companyList
          }
          //  清理原先的公司选择项
          let needClear = true
          this.selectList.companyListFiltered.forEach((cp) => {
            if (cp.id == this.formBaseData.secondParty) {
              needClear = false
            }
          })
          if (needClear) {
            this.formBaseData.secondParty = null
          }
        }
      })
    },
    /**
     * 获取当前用户能够看到的项目
     *
     * */
    // getScopeProjects() {
    //     this.$httpGetBuss(`/japi/contract/getAllProjects`)
    //         .then((res) => {
    //             if (res.data.status == 1) {
    //                 this.selectList.scopeProjects = res.data.data
    //             } else {
    //                 throw res.data.message
    //             }
    //         })
    //         .catch((err) => {
    //             console.log('获取用户关联项目失败', err)
    //             this.$messageError('获取关联项目列表失败')
    //         })
    // },
    /**
     * 获取当前用户所属部门
     *
     * */
    getDepts() {
      this.$httpGetBuss(`/japi/contract/getDepts`)
        .then((res) => {
          if (res.data.status == 1) {
            this.selectList.depts = res.data.data
          } else {
            throw res.data.message
          }
        })
        .catch((err) => {
          console.log('获取用户关联部门失败', err)
          this.$messageError('获取用户关联部门失败')
        })
    },
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        before = before.toString()
        let num = before.split('.')[0]
        let numSmall = before.split('.')[1]
        let result = [],
          counter = 0
        num = (num || 0).toString().split('')
        for (let i = num.length - 1; i >= 0; i--) {
          counter++
          result.unshift(num[i])
          if (!(counter % 3) && i != 0) {
            result.unshift(',')
          }
        }
        let after =
          numSmall === undefined
            ? result.join('')
            : result.join('') + '.' + numSmall
        return after
      } catch (e) {
        return ''
      }
    },

    //获取合同分类
    getTypeList(callback) {
      this.$httpPost(
        this.$store.state.httpHost.system +
        '/japi/dict/valuelabel/newContractType'
      )
        .then((res) => {
          if (res.data.status === 1) {
            this.selectList.type = []

            res.data.list.forEach((item) => {
              this.$set(this.selectList.type, this.selectList.type.length, item)
            })
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('contractType请求失败')
        })
    },
    //获取合同类型
    getMoldList(callback) {
      this.$httpPost(
        this.$store.state.httpHost.system + '/japi/dict/valuelabel/contractMold'
      )
        .then((res) => {
          if (res.data.status === 1) {
            this.selectList.mold = []

            res.data.list.forEach((item) => {
              this.$set(this.selectList.mold, this.selectList.mold.length, item)
            })
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('getMoldList请求失败')
        })
    },
    // //获取合同性质
    // getNatureList(callback) {
    //     this.$httpPost(
    //         this.$store.state.httpHost.system + '/japi/dict/valuelabel/contractNature'
    //     )
    //         .then((res) => {
    //             if (res.data.status === 1) {
    //                 this.selectList.nature = []
    //
    //                 res.data.list.forEach((item) => {
    //                     this.$set(this.selectList.nature, this.selectList.nature.length, item)
    //                 })
    //             } else {
    //                 this.$messageError(res.data.message)
    //             }
    //         })
    //         .catch((res) => {
    //             console.log('请求出现错误', res)
    //             this.$messageError('getNatureList请求失败')
    //         })
    // },

    //获取财务合同类型
    getFinanceList(callback) {
      this.$httpPost(
        this.$store.state.httpHost.system + '/japi/dict/valuelabel/financeType'
        // this.$store.state.httpHost.buss + '/japi/contract/valuelabel'
      )
        .then((res) => {
          if (res.data.status === 1) {
            this.selectList.finacialType = []
            res.data.list.forEach((item) => {
              this.$set(
                this.selectList.finacialType,
                this.selectList.finacialType.length,
                item
              )
            })
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('getFinanceList请求失败')
        })
    },

    //获取标段列表
    getSectionList(callback) {
      this.$httpGet(
        this.$store.state.httpHost.buss +
        '/japi/section/getByMemberCompanyId?id=null'
      )
        .then((res) => {
          if (res.data.status === 1) {
            this.selectList.sectionList = []

            res.data.data.forEach((item) => {
              this.$set(
                this.selectList.sectionList,
                this.selectList.sectionList.length,
                item
              )
            })
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('SectionList请求失败')
        })
    },

    getCompanyList() {
      this.$httpGet(
        this.$store.state.httpHost.buss + '/japi/contract/getCompanyByUser'
      )
        .then((res) => {
          console.info(res)
          this.selectList.companyList = res.data.data
          if (res.status === 200) {
            this.selectList.companyList = []

            res.data.data.forEach((item) => {
              this.$set(
                this.selectList.companyList,
                this.selectList.companyList.length,
                item
              )
            })
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('companyList请求失败')
        })
    },

    // 获取详情请求 api
    getDetail() {
      getOneForSetting(this.detailId).then((res) => {
        if (res.code === 200) {
          let data = res.data
          // 表单信息
          this.formBaseData = JSON.parse(JSON.stringify(data))
          // this.loadFiles()
          // 文件系统
          // this.$refs.cmsFileTables.getFiles()
        } else {
          // this.$messageError(res.data.message)
        }
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          // this.$messageError(this.$route.name + '获取详情请求-请求失败')
        })
    },

    /**
     * 审核提交成功的回调函数
     * */
    onAuditSubmitSuccess() {
      //  关闭查看框并刷新列表
      this.formShow = false
      setTimeout(() => {
        this.$emit('reloadList')
      }, 500)
    },
    /**
     * 选中流程动作选项时的回调函数
     * */
    onSeledAuditAction() {
    },

    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      if (this.detailType === 'build') {
        this.formBaseData.id = this.detailId
        submitSetting(this.formBaseData).then((res) => {
          if (res.code === 200) {
            // this.$messageSuccess('保存成功')
            this.detailId = res.data.id
            this.isLoading = false
            this.formShow = false
            if (callback) callback()
          } else {
            this.isLoading = false
            // this.$messageError(res.data.message)
          }
        })
          .catch((res) => {
            console.log('请求出现错误', res)
            this.isLoading = false
            // this.$messageError(this.$route.name + '提交详情-请求失败')
          })
      } else {
        this.formBaseData.id = this.detailId
        resubmitSetting(this.formBaseData).then((res) => {
          if (res.code === 200) {
            // this.$messageSuccess('保存成功')
            // this.detailId = !this.detailId ? res.data.id : this.detailId
            this.isLoading = false
            this.formShow = false;
            if (callback) callback()
          } else {
            this.isLoading = false
            // this.$messageError(res.data.message)
          }
        })
          .catch((res) => {
            console.log('请求出现错误', res)
            this.isLoading = false
            // this.$messageError(this.$route.name + '提交详情-请求失败')
          })
      }

    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(this.$store.state.httpHost.buss + url + query, params)
        .then((res) => {
          if (res.data.status === 1) {
            if (callback) callback(res.data)
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          // 清空表单内容
          this.formBaseData = {
            approveId: '',
            workContent: '',
            unit: '',
            timeUse: '',
            mark: '',
            fileName: '',
            sort: '',
            approvalType: '',
            approvalUnit: '',
            docNumber: '',
          } // 表单基本信息内容
          // 清空文件
          this.selectList.approval = []
          // 关闭弹窗
          this.formShow = false
          this.enableSectionSelection = false
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                // 绑定文件到表单
                // if (this.detailType === 'build') {
                //   this.bingFileForm(files, this.fileSystem.part[0], () => {})
                // }
                // this.$refs.cmsFileTables.bindAllFile(this.detailId)
                // this.saveFiles()
                // this.fileList = []
                // 传值给父组件刷新列表
                this.$emit('reloadList')
              })
            }
          })
          break
        // 删除
        case 'delete':
          this.$prompt('删除理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          })
            .then(({ value }) => {
              if (value === null || value === '') {
                this.$messageError('请填写删除理由后重试')
                return
              }
              this.sealDealHttp(
                res.url,
                ``,
                {
                  id: this.detailId,
                  description: value,
                },
                () => {
                  this.$messageSuccess('删除成功!')
                  this.formShow = false
                  // 传值给父组件刷新列表
                  this.$emit('reloadList')
                }
              )
            })
            .catch(() => {
              console.log('请求出现错误')
            })
          break
      }
    },
    // 上传文件前
    beforeUpload(file) {
      if (file.size > 20 * 1024 * 1024) {
        this.$messageError('上传文件大小不能超过20M')
        return
      }
      console.log(file)
      let fd = new FormData()
      fd.append('file', file)
      this.$httpPost(
        `${this.$store.state.httpHost.file}/japi/filesystem/upload?maxFileSize=${file.size}&viewByAnon=true&longLife=false`,
        fd,
        {
          headers: {
            'Content-Type':
              'multipart/form-data; boundary=----WebKitFormBoundaryIOi8qEBAFV1KN25n',
          },
        }
      )
        .then((res) => {
          if (res.data.status === 1) {
            this.selectList.file.push({
              name: file.name,
              size: file.size,
              url: res.data.link,
              id: res.data.id,
            })
            // 非新建时绑定文件
            if (this.detailType !== 'build') {
              this.bingFileForm([res.data.id], this.fileSystem.part[0])
            }
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError(this.$route.name + '上传文件前-请求失败')
        })
    },
    // 删除文件时解绑文件
    removeFile(file, fileList) {
      console.log(file, fileList)
      this.unBingFile(file.id)
      this.selectList.file = fileList
    },
    // 查看文件
    checkFile(file) {
      console.log('ssssssss' + file.name)
      this.$httpPost(
        this.$store.state.httpHost.file +
        `/japi/filesystem/getFilePreview?id=${file.id}&browserType=1`
      )
        .then((res) => {
          if (res.data.status === 1) {
            window.open(
              res.data.url.replace('/file', this.$store.state.httpHost.file)
            )
          } else if (res.data.status === 0) {
            this.$messageError(res.data.message)
          } else {
            this.$messageError('在线预览失败 ')
          } // window.location.href = res.data.url
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$toast('请求失败!')
        })
    },
    // 绑定文件到表单
    bingFileForm(fileIdsArray, part, callback) {
      if (fileIdsArray.length === 0) return
      this.$httpPost(
        this.$store.state.httpHost.file +
        '/japi/filesystem/attachment/bindBigBatch',
        [
          {
            fileid: fileIdsArray, // 文件列表
            form: this.detailId, // 表单
            sys: this.fileSystem.sys,
            module: this.fileSystem.module,
            part: part,
          },
        ]
      )
        .then((res) => {
          if (res.data.status === 1) {
            if (callback) callback()
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$toast('请求失败!')
        })
    },
    // 获取绑定的附件
    // getFiles() {
    //   let loginMessage = this.$store.getters.getLoginMessage()
    //   this.$httpGet(
    //     `${this.$store.state.httpHost.file}/japi/filesystem/attachment/getFilesByAttach?sys=${this.fileSystem.sys}&module=${this.fileSystem.module}&form=${this.detailId}`
    //   )
    //     .then((res) => {
    //       if (res.data.status === 1) {
    //         this.fileSystem.attachId = res.data.attachid
    //         let files = []
    //         let imgs = []
    //         if (
    //           res.data.attachinfos[0] &&
    //           res.data.attachinfos[0].part === 'one'
    //         ) {
    //           files = res.data.attachinfos[0].fileInfo
    //         } else if (
    //           res.data.attachinfos[0] &&
    //           res.data.attachinfos[0].part === 'two'
    //         ) {
    //           imgs = res.data.attachinfos[0].fileInfo
    //         }
    //         if (
    //           res.data.attachinfos[1] &&
    //           res.data.attachinfos[1].part === 'one'
    //         ) {
    //           files = res.data.attachinfos[1].fileInfo
    //         } else if (
    //           res.data.attachinfos[1] &&
    //           res.data.attachinfos[1].part === 'two'
    //         ) {
    //           imgs = res.data.attachinfos[1].fileInfo
    //         }
    //         files.forEach((item) => {
    //           this.selectList.file.push({
    //             name: item.name,
    //             size: item.size,
    //             link: item.link,
    //             id: item.id,
    //             url: this.$store.state.httpHost.file + item.link,
    //           })
    //         })
    //         imgs.forEach((item) => {
    //           this.landImgList.push({
    //             name: item.name,
    //             size: item.size,
    //             link: item.link,
    //             id: item.id,
    //             url: this.$store.state.httpHost.file + item.link,
    //           })
    //         })
    //       } else {
    //         this.$messageError(res.data.message)
    //       }
    //     })
    //     .catch((res) => {
    //       console.log('请求出现错误', res)
    //       this.$messageError('请求失败!')
    //     })
    // },
    // 解绑已绑定的文件
    unBingFile(fileId, callback) {
      this.$httpPost(
        `${this.$store.state.httpHost.file}/japi/filesystem/attachment/removeBindBatch?attachment=${this.fileSystem.attachId}&fileInfo=${fileId}`
      )
        .then((res) => {
          if (callback) callback()
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError('请求失败!')
        })
    },
    handleClick() { },
    /**
     * 获取项目关联的标段
     * @param projectId
     */
    getProjectSection(projectId, callback) {
      this.$httpGetBuss(
        `/japi/contract/getProjectSectionByMutiProject?pid=${projectId}&id=${this.detailId}&typeId=${this.formBaseData.type}`
      )
        .then((res) => {
          if (res.data.status == 1) {
            this.selectList.sectionList = res.data.data
            this.formBaseData.sectionIds = []
            if (callback) callback()
          } else {
            throw res.data.message
          }
        })
        .catch((err) => {
          console.log('获取项目关联的标段失败', err)
          this.$messageError('获取项目关联的标段失败')
        })
    },
    /**
     *显示删除按钮
     * @param row
     */
    buttonDelShow(row) {
      let flag = false
      if (
        (this.detailType === 'build' || this.detailType === 'edit') &&
        row.file[0].realName !== '' &&
        !row.isNeed
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport&&row.file[0].realName!==''&&!row.isNeed) {
      //   flag=true
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },

    autoFill(id, fileId, param, callback) {
      let type = ''
      if (this.detailType === 'build') {
        type = 'build'
      }

      this.$httpPost(
        this.$store.state.httpHost.buss + '/japi/contractapply/autoFill',
        {
          id: id,
          fileId: fileId,
          type: type,
          content: param,
        }
      )
        .then((res) => {
          if (res.data.status === 1) {
            if (callback) callback()
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          this.$messageError(this.$route.name + '请求失败')
        })
    },

    /**
     *控制显示暂无文件
     * @param row
     */
    showNone(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      return flag
    },
    /**
     * 控制查看按钮显示
     * @param row
     */
    buttonCheckShow(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName !== ''
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=false
      // }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    /**
     * 控制上传按钮显示
     * @param row
     * @returns {boolean}
     */
    buttonUploadShow(row) {
      let flag = false
      if (
        this.detailType === 'build' ||
        this.detailType === 'edit' ||
        this.detailType === 'approve'
      ) {
        flag = true
      }
      // 经办人操作时
      // if ((this.detailType!=='build'&&this.detailType!=='edit'&&this.detailType!=='check')&&this.isReport) {
      //   flag=true
      // }
      return flag
    },
    tableChange(val) {
      this.$set(this, 'buildUnitTable', [...val])
    },
    tableChange_htqd(val) {
      this.$set(this, 'buildUnitTable_htqd', [...val])
    },
  },
}
</script>

<style scoped lang="scss">
.el-select.half {
  width: 250px;
}

.el-select.fill {
  width: 800px;
}

.contract_input {
  width: 250px;
}

.contract_input2 {
  width: 240px;
}

.el-input .el-select {
  width: 130px;
}

.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}
</style>
